using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;

namespace MiniPac.Components
{
	class Maze : IEnumerable
	{
		int X;	// Pos X
		int Y;	// Pos Y

		private Tile[,] maze;
		
		public Maze(int x, int y)
		{
			X = x;
			Y = y;
			maze = new Tile[R.MazeArray.GetLength(0),R.MazeArray.GetLength(1)];
			InitTiles();
		}

		public Tile this[int x, int y]
		{
			get
			{
#if DEBUG        
				if (x >= R.MazeXSize)
				{
					Debug.WriteLine("X out of bound, X=" + x);
				} else if (y >= R.MazeYSize)
				{
					Debug.WriteLine("Y out of bound, Y=" + x);
				}else
				{
					Debug.WriteLine("x, y are OK");
				}
#endif
				x = x >= R.MazeXSize ? R.MazeXSize-1 : (x <= 0 ? 0 : x);
				y = y >= R.MazeYSize ? R.MazeYSize-1 : (y <= 0 ? 0 : y);
				return maze[y, x];
			}
			set { maze[y, x] = value;}
		}

		public int MazeTileSizeX { get { return maze.GetLength(1); } }
		public int MazeTileSizeY { get { return maze.GetLength(0); } }

		public int MazePixelSizeX { get { return MazeTileSizeX * R.Size; } }
		public int MazePixelSizeY { get { return MazeTileSizeY * R.Size; } }

		private void InitTiles()
		{
			int t, dx, dy, idx;
			Tile tc;

			for (int y = 0; y < MazeTileSizeY; y++)
			{
				for (int x = 0; x < MazeTileSizeX; x++)
				{
					t = R.MazeArray[y, x];
					dx = X + x*R.Size;
					dy = Y + y*R.Size;

					idx = y*MazeTileSizeX + x;

					switch (t)
					{
						
						case 1:
							this[x, y] = (new Tile(dx, dy, Color.Blue, t));
							break;
						case 3:
							this[x, y] = (new Tile(dx, dy, Color.LightPink, t));
							break;
						default:
							this[x, y] = (new Tile(dx, dy, Color.Black, t));
							break;
					}
				}
			}
		}

		public void Draw(SpriteBatch sb)
		{
			foreach (var tile in maze)
			{
				tile.Draw(sb);
			}
		}

		#region Implementation of IEnumerable

		public IEnumerator GetEnumerator()
		{
			return maze.GetEnumerator();
		}

		#endregion
	}
}
